<?php
/**
 *  * author 韩天尊
 * Date: 2022/3/9
 * Email: <724700483@qq.com>
 */

namespace App\HttpController\Api\Admin;

use App\HttpController\Api\ApiBase;
use App\Model\RoleModel;
use EasySwoole\EasySwoole\Core;
use EasySwoole\EasySwoole\Trigger;
use EasySwoole\Http\Message\Status;
use EasySwoole\HttpAnnotation\Exception\Annotation\ParamValidateError;
use Exception;

abstract class AdminBase extends ApiBase
{
    /*权限规则表：
    id=>权限id pid=>权限父id is_menu=>0(是否为菜单) rule=>路径(auth/rule/action) function_name=>操作名称 methods=>"GET"||"PATCH"||"DELETE"||"POST" icon=>图标 weight=>权重 status=>(0|1)启用状态
    */

    /*角色组
     * id=>角色组id pid=>父角色组id name=>角色组名称 rule_ids=>权限id status=>>(0|1)启用状态
     */

    /**
     * @param string|null $action
     * @return bool|null
     * * author 韩天尊
     * * date 2022-03-15 10:17
     * @throws Exception
     */
    public function onRequest(?string $action): ?bool
    {
        if (parent::onRequest($action)) {
            // 白名单判断
            if (in_array($action, $this->whiteList)) {
                return true;
            }
            // 获取登入信息
            $request = $this->request();
            if(isset($request->getHeaders()['token'])==false || empty($request->getHeaders()['token'])){
                $this->failure("empty token", [], Status::CODE_UNAUTHORIZED);
                $this->writeBack->write_back_type = false; return false;
            }
            $checkData = verifyToken($request->getHeaders()['token'][0], "ADMIN");
            if ($checkData->execute == false) {
                $this->failure($checkData->message, [], Status::CODE_UNAUTHORIZED);
                $this->writeBack->write_back_type = false; return false;
            }
            $this->currentTokenActionId = $checkData->data['objectInfo']['id'];
            $this->currentTokenOtherInfo = $checkData->data['objectInfo']['otherInfo'];
            $this->currentTokenServerInfo = $checkData->data['serverInfo'];

            //查出管理员角色id并检测权限
            //$this->checkPermission($action, $request->getMethod(), $role_id);
            return true;
        }
        return false;
    }

    /** 检测权限
     * @param string $action
     * *    author 韩天尊
     */
    public function checkPermission(string $action, $method, $role_id): bool
    {
        return (new RoleModel())->checkRoleRule($action, $method,$role_id);
    }
}